#! /usr/bin/env bash

# 初始化仓库

# 当前执行脚本所在的文件夹
SCRIPT_DIR=$(cd "$(dirname "$0")";
pwd)

SCRIPT_NAME=$1

function echo_usage() {
    echo "Usage:"
    echo "  $SCRIPT_NAME <os> <target>"
    #    echo "      os: linux|android"
    #    echo "      linux target: i386|x86_64"
    echo "      os: android"
    echo "      android target: armv5|armv7a|arm64|x86|x86_64"
    exit 1
}

OS=$2
TARGET=$3

case ${OS} in

    linux | android)
    ;;

    *)
        echo "不支持编译'$OS'平台的库"
        echo_usage
    ;;

esac

# 远程仓库地址
REMOTE_REPO=$4
# 本地仓库地址
LOCAL_REPO=$5
# 构建目标地址
BUILD_DEST=$6
# 代码分支/TAG
REPO_VER=$7

# 如果脚本发生错误，停止运行
set -e

TOOLS=${SCRIPT_DIR}/tools

function pull_repo() {
    echo "pull $REMOTE_REPO to $LOCAL_REPO ..."
    sh ${TOOLS}/pull-repo-base.sh ${REMOTE_REPO} ${LOCAL_REPO}

    echo "pull $LOCAL_REPO to $BUILD_DEST ..."
    sh ${TOOLS}/pull-repo-ref.sh ${REMOTE_REPO} ${LOCAL_REPO} ${BUILD_DEST}

    echo "checkout $REPO_VER ..."
    cd ${BUILD_DEST}
    { # try 
        git checkout ${REPO_VER} -B build-${REPO_VER}
    } || { # catch
        git checkout ${REPO_VER}
        git branch -m ${REPO_VER} build-${REPO_VER}
    }
    cd -
}

case ${TARGET} in

    i386 | x86_64)
        if [[ ${OS} == "linux" ]]; then
            pull_repo
        else
            echo "'$OS'平台不支持编译'$TARGET'目标"
            echo_usage
        fi
    ;;

    armv5 | armv7a | arm64 | x86 | x86_64)
        if [[ ${OS} == "android" ]]; then
            pull_repo
        else
            echo "'$OS'平台不支持编译'$TARGET'目标"
            echo_usage
        fi
    ;;

    *)
        echo "'$OS'平台不支持编译'$TARGET'目标"
        exit 1
    ;;
esac
